package com.zzb.projectfactory.framework.mysqlexplain.service;

import com.alibaba.druid.pool.DruidDataSource;
import com.zzb.projectfactory.framework.mysqlexplain.entity.MysqlExplain;
import com.zzb.projectfactory.framework.query.AnnotationColumnRowMapper;
import com.zzb.projectfactory.framework.utils.SQLUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * mysqlExplainService
 * Created by zhangzhenbin on 17-3-9.
 */
@Service
public class MysqlExplainService {
    private static final Logger logger = LoggerFactory.getLogger(MysqlExplainService.class);

    public List<MysqlExplain> explainsSql(String sql, String url , String username , String password){
        final List<MysqlExplain> list = new ArrayList<>();
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        if(SQLUtils.sqlIsValid(sql)){
            String explainSql = "explain " + sql;
            try {
                List<MysqlExplain> query = jdbcTemplate.query(explainSql, new AnnotationColumnRowMapper<MysqlExplain>(MysqlExplain.class));
                list.addAll(query);
            } catch (DataAccessException e) {
                logger.error("执行mysqlExplain失败，执行sql["+explainSql+"]");
            }
        }
        dataSource.close();
        return list;
    }
}
